<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小西瓜 < 751707632@qq.com>
// +----------------------------------------------------------------------
namespace app\api\controller;

use app\api\controller\Common;
use think\Validate;
use think\Db;

class AuthController extends CommonController
{
    /**
     * 提交登录token
     */
    public function verifyLogin()
    {
        $data = request()->param(); // 获取用户传参
        // 检查字段要求
        $rule = [
            'token_key'  => 'require',
            'user_id'   => 'require',
        ];
        $validate = new Validate($rule);
        if(!$validate->check($data)){
            return returnJson(400, $validate->getError());
        }

        if ( Db::name('ims_member')->where('token_key', $data['token_key'])->value('id') ) {
            return returnJson(400, 'token_key已被使用！');
        }
        $res = json_decode($this->post(STAFF_LOGIN_USER, staffTokenData('', '', $data['token_key'])));
        if ( $res->result == 'OK' ) {
            $dataSave['token_key'] = $data['token_key'];
            $dataSave['token_time'] = time()+1800;
            $dataSave['login_ip'] = request()->ip();
            $dataSave['login_time'] = date('Y-m-d H:i:s', time());
            if ($this->user_id=Db::name('ims_member')->where('staff_number', $data['user_id'])->value('id')) {
                Db::name('ims_member')->where('staff_number', $data['user_id'])->update($dataSave); // 修改token时效  
            } else {
                $this->memberAdd($dataSave, $data['user_id']); // 添加用户信息
            }
            return returnJson(200, 'success');
        } else {
            return returnJson(400, $res->msg);
        }
    }

    /**
     * 登录用户不存在添加用户信息
     * @param  array $dataSave  用户部分信息
     * @param  string $staff_number 员工工号
     * @return  null
     */
    public function memberAdd($dataSave=array(), $staff_number='')
    {
        $userInfo = json_decode($this->post(STAFF_USER_ONE_USER, staffTokenDataALL('PXS000301', 'PxS000301xuZHenG', $staff_number)));
        $dataSave['staff_number']   = $userInfo->user_id;
        if ($dataSave['staff_number'] != '' && $dataSave['staff_number'] != null) { 
            $dataSave['staff_name']     = $userInfo->user_name;
            $dataSave['staff_duty']     = $userInfo->user_duty;
            $dataSave['staff_pic']      = $userInfo->user_picture;
            $dataSave['staff_deptname'] = $userInfo->deptname;
            $dataSave['staff_deptid']   = $userInfo->deptid;
            if ( $this->user_id=Db::name('ims_member')->where('staff_number',$userInfo->user_id)->value('id') ) {
                $dataSave['update_time']     = date('Y-m-d H:i:s', time());
                Db::name('ims_member')->where('staff_number', $userInfo->user_id)->update($dataSave); // 更新数据
            } else {
                $dataSave['create_time']     = date('Y-m-d H:i:s', time());
                $uid[$v]=Db::name('ims_member')->insertGetId($dataSave); // 添加数据
            }
        }
    }
    

    /**
     * 退出登录
     */
    public function loginOut()
    {
        $data = request()->param(); // 获取用户传参
        // 检查字段要求
        $rule = [
            'token_key'  => 'require',
            'user_id'   => 'require',
        ];
        $validate = new Validate($rule);
        if(!$validate->check($data)){
            return returnJson(400, $validate->getError());
        } 
        // 检查登录
        $verifyToken = $this->verifyToken($data['token_key']);
        if ( $verifyToken != '1111') return $verifyToken;

        // 查找用户
        $token_key = Db::name('ims_member')->where('id',$data['user_id'])->value('token_key');
        if (!$token_key || $token_key != $data['token_key']) return returnJson(400, 'false');
        // 修改token过期时间
        if (Db::name('ims_member')->where('id', $data['user_id'])->update(['token_key'=>'1','token_time'=>time()-1])){
            return returnJson(200, 'success');
        }
        return returnJson(400, 'false');
    }

    /**
     * [userList 获取员工列表]
     * @return [array] [description]
     */
    public function userList()
    {
        $param = request()->param(); // 获取用户传参
        
        // 数据验证
        $rule = [
            'token_key' => 'require',
            'page'  => 'number',
            'limit'   => 'number',
            'userduty'  => 'number',
        ];  
        $validate = new Validate($rule);
        if(!$validate->check($param)){
            return returnJson(400, $validate->getError());
        }
        // 检查登录
        $verifyToken = $this->verifyToken($param['token_key']);
        if ( $verifyToken != '1111') return $verifyToken;

        if ( isset($param['page']) && !empty($param['page']) ) $this->page = $param['page'];
        if ( isset($param['limit']) && !empty($param['limit']) ) $this->limit = $param['limit'];
        if ( isset($param['userduty']) && !empty($param['userduty']) ) {
            if ( !($duty = Db::name('ims_member_duty')->where('id', $param['userduty'])->value('duty')) ) return returnJson(400, '职称不存在');
        };

        // 获取员工列表
        $user = json_decode($this->post(STAFF_USER_ALL_USER_PAGE.'/'.$this->page.'/'.$this->limit, staffTokenDataALL('', '', '', '', '', $duty)));
        $userList = array();
        foreach ($user as $k => $v) {
            $userList[$k]['deptid'] = $v->deptid;
            $userList[$k]['deptname'] = $v->deptname;
            $userList[$k]['user_id'] = $v->user_id;
            $userList[$k]['user_name'] = $v->user_name;
            $userList[$k]['user_deptment'] = $v->user_deptment;
            $userList[$k]['user_duty'] = $v->user_duty;
        } 

        // $this->traceLog('请求了[员工列表]接口'); // 操作日志
        return returnJson(200, 'userList', $userList);
    }

    /**
     * [userDutyList 获取员工职称]
     * @return [json] [description]
     */
    public function userDutyList()
    {
        $param = request()->param(); // 获取用户传参
        // 数据验证
        $rule = [
            'token_key' => 'require',
        ];  
        $validate = new Validate($rule);
        if(!$validate->check($param)){
            return returnJson(400, $validate->getError());
        }
        // 检查登录
        $verifyToken = $this->verifyToken($param['token_key']);
        if ( $verifyToken != '1111') return $verifyToken;

        $dutyList = Db::name('ims_member_duty')->field('id, duty')->select()->toArray();

        // $this->traceLog('请求了[获取员工职称]接口'); // 操作日志
        return returnJson(200, 'userDutyList', $dutyList);
    }

    /**
     * [LiveNotifyReceive 接受直播录制回调]
     */
    public function LiveNotifyReceive()
    {
        // 获取回调数据
        $json = file_get_contents('php://input');
        $data = json_decode($json, true);

        if ( $data['app'] == 'meeting' ) {
            $save['store_link'] = 'http://files.puxiansheng.net/'.$data['uri'];
            $res = Db::name('ims_meeting_live')->where('id', $data['stream'])->update($save);
            if ( $res ) return 'SUCCESS';
        } elseif ( $data['app'] == 'straming' ) {
            $save['store_link'] = 'http://files.puxiansheng.net/'.$data['uri'];
            $res = Db::name('ims_straming_live')->where('id', $data['stream'])->update($save);
            if ( $res ) return 'SUCCESS';
        }
        return 'ERROR';
    }
}